package com.example.client;

import static java.lang.System.out;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.example.client.manager.ClientManager;
import com.example.client.manager.ICommunicator;

public class ChatClient extends JFrame implements ActionListener, ICommunicator {
	String uname;
	PrintWriter pw;

	private JTextArea taMessages;
	JTextField tfInput;
	JButton btnSend, btnExit;
	Socket client;

	ClientManager clientManager = null;

	public ChatClient(String uname, String servername) throws Exception {
		super(uname); // set title for frame
		this.uname = uname;

		clientManager = new ClientManager(this);

		clientManager.getWriter().println(uname); // send name to server

		buildInterface();

	}

	public void buildInterface() {
		btnSend = new JButton("Send");
		btnExit = new JButton("Exit");
		taMessages = new JTextArea();
		taMessages.setRows(10);
		taMessages.setColumns(50);
		taMessages.setEditable(false);
		tfInput = new JTextField(50);
		JScrollPane sp = new JScrollPane(taMessages,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		add(sp, "Center");
		JPanel bp = new JPanel(new FlowLayout());
		bp.add(tfInput);
		bp.add(btnSend);
		bp.add(btnExit);
		add(bp, "South");
		btnSend.addActionListener(this);
		btnExit.addActionListener(this);
		setSize(500, 300);
		setVisible(true);
		pack();
	}

	public JTextArea getMessage() {
		return this.taMessages;
	}

	public void actionPerformed(ActionEvent evt) {
		if (evt.getSource() == btnExit) {
			pw.println("end"); // send end to server so that server know about
								// the termination
			System.exit(0);
		} else {
			// send message to server
			this.clientManager.getWriter().println(tfInput.getText());
		}
	}

	public static void main(String... args) {

		// take username from user
		String name = JOptionPane.showInputDialog(null, "Enter your name :",
				"Username", JOptionPane.PLAIN_MESSAGE);
		String servername = "localhost";
		try {
			new ChatClient(name, servername);
		} catch (Exception ex) {
			out.println("Error --> " + ex.getMessage());
		}

	} // end of main

	
	@Override
	public void getDataFromServer(String data) {

		System.out.println("Data received:: " + data);
		taMessages.append(data);
		taMessages.append("\n");

	}
} // end of client